<?php
define("IS_MAIN", true);
require "./modules/decto26.php";
require "./modules/set.php";
if ($_SERVER["REQUEST_METHOD"] != "GET") {
	echo '{"code":"error","message":"请求方法不正确"}';
	exit;
}
if ((isset($_COOKIE["htqw_share_setup_password"]) && isset($_COOKIE["htqw_share_setup_name"]) && isset($_COOKIE["htqw_share_setup_email"]) && isset($_COOKIE["htqw_share_setup_code"]) && isset($_COOKIE["htqw_share_setup_code_id"])) == false) {
	echo '{"code":"error","message":"缺少COOKIE，请确保信息是否全部填写正确"}';
	exit;
}

header("Content-Type: application/json;charset=utf8");
$password = $_COOKIE["htqw_share_setup_password"];
$name = $_COOKIE["htqw_share_setup_name"];
$email = $_COOKIE["htqw_share_setup_email"];
$code = $_COOKIE["htqw_share_setup_code"];
$codeid = $_COOKIE["htqw_share_setup_code_id"];

$conn = mysqli_connect($app["sql"]["host"], $app["sql"]["user"], $app["sql"]["password"], $app["sql"]["dbname"], $app["sql"]["port"]);
if ($conn->connect_errno) {
	echo '{"code":"error","message":"数据库链接失败"}';
	exit;
}

$stmt = $conn->prepare("select * from code where id=?");
$stmt->bind_param("s", $codeid);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 0) {
	mysqli_close($conn);
	echo '{"code":"error","message":"授权码错误！"}';
	exit;
}
$row = $result->fetch_assoc();
if ($row["code"] != $code) {
	mysqli_close($conn);
	echo '{"code":"error","message":"授权码错误！"}';
	exit;
}
if (time() - intval($row["time"]) > 600) {
	mysqli_close($conn);
	echo '{"code":"error","message":"授权码已失效！"}';
	exit;
}

$cmd = $conn->query("select count(*) as rows from users");
if (!$cmd) {
	mysqli_close($conn);
	echo '{"code":"error","message":"操作数据库时出现错误"}';
	exit;
}

$users_rows = $cmd->fetch_assoc();
$insertInto = $conn->prepare("insert into users (name, id, op, password, email) values (?, ?, ?, ?, ?);");
$ajdojd = intval($users_rows["rows"])+1;
$id = decToBase26($ajdojd);

$op = "false";
$insertInto->bind_param("sssss", $name, $id, $op, $password, $email);
if (!$insertInto->execute()) {
	mysqli_close($conn);
	echo '{"code":"error","message":"注册失败！"}';
	exit;
}
$sql = "select * from users where id='" . $id . "'";
$user = $conn->query($sql);
$user = $user->fetch_assoc();

setcookie("htqw_share_user", json_encode($user), time() + 60 * 24 * 30, "/");
mysqli_close($conn);
copy("../images/user.png", "../users/" . $id . ".png");
echo '{"code":"success"}';
